/**
 * com.dingjian.basedata.person.service.impl.PersonServiceImpl.java
 */
package com.dingjian.basedata.person.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.dingjian.base.dao.BaseDao;
import com.dingjian.base.service.impl.BaseServiceImpl;
import com.dingjian.base.util.StringUtils;
import com.dingjian.basedata.person.dao.PersonDao;
import com.dingjian.basedata.person.dao.PersonPositionDao;
import com.dingjian.basedata.person.model.Person;
import com.dingjian.basedata.person.model.PersonPosition;
import com.dingjian.basedata.person.service.PersonService;

/**
 * @author FengMy
 *
 * @since 2012-10-9
 */
@Component(value="personService")
@Transactional
public class PersonServiceImpl extends BaseServiceImpl<Person> implements
		PersonService {
	@Autowired
	private PersonDao personDao;
	@Autowired
	private PersonPositionDao personPositionDao;
	@Override
	protected BaseDao getDao() {
		return personDao;
	}
	@Override
	public void addPerson(Person person, List<PersonPosition> personPosition) {
		super.addEntity(person);
		if(personPosition!=null && personPosition.size() > 0){
			for(PersonPosition pp : personPosition){
				pp.setPerson(person);
			}
			personPositionDao.addBatch(personPosition);
		}
	}
	@Override
	public void updatePerson(Person person, List<PersonPosition> personPosition) {
		super.updateEntity(person);
		List<PersonPosition> old = personPositionDao.getByPerson(person.getId());
		List<PersonPosition> newPP = new ArrayList<PersonPosition>();
		List<PersonPosition> update = new ArrayList<PersonPosition>();
		Iterator<PersonPosition> nIter = personPosition.iterator();
		while(nIter.hasNext()){
			PersonPosition pp = nIter.next();
			if(StringUtils.isEmpty(pp.getId())){
				pp.setPerson(person);
				newPP.add(pp);
				nIter.remove();
			}
		}
		personPositionDao.addBatch(newPP);
		Iterator<PersonPosition> iterator = old.iterator();
		while(iterator.hasNext()){
			PersonPosition pp = iterator.next();
			for(PersonPosition p : personPosition){
				if(pp.getId().equals(p.getId())){
					p.setPerson(person);
					p.setEffectDate(pp.getEffectDate());
					update.add(p);
					iterator.remove();
				}
			}
		}
		personPositionDao.updateBatch(update);
		List<String> ids = new ArrayList<String>();
		for(PersonPosition p : old){
			ids.add(p.getId());
		}
		personPositionDao.deleteBatch(ids);
	}
}
